package z_mxsTest.testCleanMutiLangCommonWithList;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

/**
 * 规则加载器 - 负责读取targetlist.txt中的匹配规则
 */
public class RuleLoader {
    //private final CommentCleanerApplication mainApp;
    private final LogUtils logUtils;

    public RuleLoader(CommentCleanerApplication mainApp, LogUtils logUtils) {
        //this.mainApp = mainApp;
        this.logUtils = logUtils;
    }

    public void loadRules(File rootDir, List<String> ruleList, JTextArea displayArea) {
        ruleList.clear();
        StringBuilder displayText = new StringBuilder();
        File ruleFile = new File(rootDir, "targetlist.txt");

        if (!ruleFile.exists() || !ruleFile.isFile()) {
            displayArea.setText("❌ 未找到targetlist.txt\n提示：在根目录创建该文件");
            logUtils.log("警告：根目录下无targetlist.txt");
            return;
        }

        try (BufferedReader reader = Files.newBufferedReader(ruleFile.toPath(), StandardCharsets.UTF_8)) {
            String line;
            int lineNum = 0;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                lineNum++;
                
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                
                ruleList.add(line);
                displayText.append(lineNum).append(". ").append(line).append("\n");
            }

            if (ruleList.isEmpty()) {
                displayArea.setText("⚠️ 无有效规则（非空且非#开头的行）");
            } else {
                displayText.append("\n✅ 共加载 ").append(ruleList.size()).append(" 条规则");
                displayArea.setText(displayText.toString());
            }
            logUtils.log("加载完成，有效规则：" + ruleList.size() + "条");

        } catch (IOException e) {
            displayArea.setText("❌ 读取规则失败：" + e.getMessage());
            logUtils.log("错误：读取targetlist.txt异常 - " + e.getMessage());
        }
    }
}